package base.annotation_demo.demo_02;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * ORM: Object Relationship Mapping  对象关系映射
 *
 * - 类和表结构对应
 * - 属性和字段对应
 * - 对象和记录对应
 *
 * 利用反射和注解实现的一个简单ORM框架生成SQL
 */
@Slf4j
public class ORM {
    public static String querySQL(Student student) throws IllegalAccessException {
        StringBuilder sb = new StringBuilder();
        Class<?> clazz = student.getClass();
        // 如果该类上没有标注 @TabAnnotation 注解，则返回
        if (!clazz.isAnnotationPresent(TabAnnotation.class)) {
            return null;
        }else{
            TabAnnotation annotation = clazz.getAnnotation(TabAnnotation.class);
            String tableName;
            tableName = annotation.value();
            sb.append("select * from ").append(tableName).append(" where 1=1 ");
        }

        Field[] fields = clazz.getDeclaredFields();
//        log.info("{}", fields.length); //3
        for (Field field : fields) {
//            log.info("{} -> {}", field, field.isAnnotationPresent(FieldAnnotation.class));
            // 如果该属性上没有标注 @FieldAnnotation 注解，则返回不需要拼接SQL字符串
            if (!field.isAnnotationPresent(FieldAnnotation.class)) {
                return null;
            }else{
                FieldAnnotation annotation = field.getAnnotation(FieldAnnotation.class);
                String columnName = annotation.columnName();
                String type = annotation.type();
                int length = annotation.length();

                String fieldName = field.getName();
                String getMethodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);

                field.setAccessible(true);// private 修饰符可见
                sb.append(" and ").append(columnName).append(" = ");
                if (type.equals("int")) {
//                  sb.append(student.getId());
                    sb.append(field.get(student));
                }else if(type.equals("varchar")){
                    sb.append("'").append(field.get(student)).append("'");
                }
            }
        }
        return sb.toString();
    }
}
